package com.atguigu.structures.sparsearray;

/**
 * 稀疏数组和二维数组互转
 *
 * @author XR-8
 * @create 2020-09-22
 */
public class SparseArray {

    public static void main(String[] args) {
        int[][] chess = new int[9][11];
        chess[1][2] = 1;
        chess[2][3] = 2;
        System.out.println("chess.length="+chess.length);
        System.out.println("原数组为：");
        for (int[] ints : chess) {
            for (int anInt : ints) {
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }

        //二维数组转稀疏数组
        int count = 0;
        for (int i = 0; i < chess.length; i++) {
            for (int j = 0; j < chess[i].length; j++) {
                if(chess[i][j]!=0){
                    count++;
                }
            }
        }
        int[][] sparseArray = new int[count+1][3];
        sparseArray[0][0] = 9;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = count;
        int k = 0;
        for (int i = 0; i < chess.length; i++) {
            for (int j = 0; j < chess[i].length; j++) {
                if(chess[i][j]!=0){
                    k++;
                    sparseArray[k][0]=i;
                    sparseArray[k][1]=j;
                    sparseArray[k][2]=chess[i][j];
                }
            }
        }
        System.out.println("转化后的稀疏数组为：");
        for (int[] ints : sparseArray) {
            System.out.println(ints[0]+"\t"+ints[1]+"\t"+ints[2]);
        }

        //稀疏数组转二维数组
        int[][] newArray = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i <= sparseArray[0][2]; i++) {
            newArray[sparseArray[i][0]][sparseArray[i][1]]=sparseArray[i][2];
        }
        System.out.println("再次转化后的二维数组为：");
        for (int[] ints : newArray) {
            for (int anInt : ints) {
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }
    }
}
